/**
 * @file userUsart.c
 * @author  xiaowine (xiaowine@sina.cn)
 * @brief
 * @version 01.00
 * @date    2025-08-31
 *
 * @copyright Copyright (c) {2020}  xiaowine
 *
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2025-08-31 <td>1.0     <td>wangh     <td>内容
 * </table>
 * ******************************************************************
 * *                   .::::
 * *                 .::::::::
 * *                ::::::::::
 * *             ..:::::::::::
 * *          '::::::::::::
 * *            .:::::::::
 * *       '::::::::::::::..        女神助攻,流量冲天
 * *            ..::::::::::::.     永不宕机,代码无bug
 * *          ``:::::::::::::::
 * *           ::::``:::::::::'        .:::
 * *          ::::'   ':::::'       .::::::::
 * *        .::::'      ::::     .:::::::'::::
 * *       .:::'       :::::  .:::::::::' ':::::
 * *      .::'        :::::.:::::::::'      ':::::
 * *     .::'         ::::::::::::::'         ``::::
 * * ...:::           ::::::::::::'              ``::
 * *```` ':.          ':::::::::'                  ::::.
 * *                   '.:::::'                    ':'````.
 * ******************************************************************
 */

/* Private includes ----------------------------------------------------------*/
#include "userUsart.h"
#include <string.h>
//////////////////////////////////////////////////////////////////////////////////
// 如果使用os,则包括下面的头文件即可.
#if SYSTEM_SUPPORT_OS
#include "includes.h" //os 使用
#endif

/* Private typedef -----------------------------------------------------------*/

/* Private define ------------------------------------------------------------*/

/* Private macro -------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/

uint8_t tx1DMAbuffer[USART_REC_LEN] = {0x0A, 0x03, 0x00, 0x16, 0x00, 0x05, 0x65, 0x76};
uint8_t rx1DMAbuffer[USART_REC_LEN] = {0};
uint8_t rx1Count = 0;
uint8_t rx1Buffer[USART_REC_LEN] = {0};

volatile _TKS_FLAGA_type CONNECTEFlags = {0};

const uint8_t buffTrail[2] = {0x0d, 0x0a};
// 接收状态
// bit15，	接收完成标志
// bit14，	接收到0x0d
// bit13~0，	接收到的有效字节数目
uint16_t USART_RX_STA = 0; // 接收状态标记

//////////////////////////////////////////////////////////////////////////////////

//********************************************************************************

//////////////////////////////////////////////////////////////////////////////////
// 加入以下代码,支持printf函数,而不需要选择use MicroLIB
// #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#if 1
// #pragma import(__use_no_semihosting)
// 标准库需要的支持函数
struct __FILE
{
    int handle;
};

FILE __stdout;
// 定义_sys_exit()以避免使用半主机模式
void _sys_exit(int x)
{
    x = x;
}
// 重定义fputc函数
int fputc(int ch, FILE *f)
{
    uint8_t temp[1] = {ch};
    HAL_UART_Transmit(&huart1, temp, 1, 10);
    return ch;
}
#endif

#if EN_USART1_RX // 如果使能了接收
// 串口1中断服务程序
// 注意,读取USARTx->SR能避免莫名其妙的错误

/**
 * @brief  Reception Event Callback (Rx event notification called after use of advanced reception service).
 * @param  huart UART handle
 * @param  Size  Number of data available in application reception buffer (indicates a position in
 *               reception buffer until which, data are available)
 * @retval None
 */
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
    /* Prevent unused argument(s) compilation warning */
    UNUSED(huart);
    UNUSED(Size);

    /* NOTE : This function should not be modified, when the callback is needed,
              the HAL_UARTEx_RxEventCallback can be implemented in the user file.
     */
    if (huart == &huart1)
    {
        if (Size > 0)
        {
            if (rx1Count + Size > USART_REC_LEN)
                rx1Count = 0;
            memcpy(rx1Buffer + rx1Count, rx1DMAbuffer, Size);
            rx1Count += Size;

            if (rx1Count >= 2)
            {
                if (memcmp(&rx1Buffer[rx1Count - 2], buffTrail, 2) == 0)
                {
                    USART_RX_STA |= 0xc000; // 接收完成了
                }
            }
            memset(rx1DMAbuffer, 0, Size); // 清零接收缓冲区
        }
        HAL_UARTEx_ReceiveToIdle_DMA(&huart1, rx1DMAbuffer, USART_REC_LEN);
        __HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
    }
}

/**
 * @brief  UART error callback.
 * @param  huart UART handle.
 * @retval None
 */
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
    /* Prevent unused argument(s) compilation warning */
    UNUSED(huart);

    /* NOTE : This function should not be modified, when the callback is needed,
              the HAL_UART_ErrorCallback can be implemented in the user file.
     */
    if (HAL_UART_GetError(huart) & HAL_UART_ERROR_ORE)
    {
        __HAL_UART_FLUSH_DRREGISTER(huart); // 读DR寄存器，就可以清除ORE错误标志位
    }
    if (huart == &huart1)
    {
        HAL_UARTEx_ReceiveToIdle_DMA(&huart1, rx1DMAbuffer, USART_REC_LEN);
        __HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
    }
}

#endif
